/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.com.wholeconsulting.pacc.gui.fluidos;

import ar.com.wholeconsulting.pacc.gui.aceros.FrameAceros;
import ar.com.wholeconsulting.pacc.gui.utils.frame.SaveOnCloseFrame;
import ar.com.wholeconsulting.pacc.model.Fluido;
import ar.com.wholeconsulting.pacc.persistance.JPASession;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author Duco Pablo
 */
public class FrameFluidos extends SaveOnCloseFrame {

    private List<Fluido> newObjects = new LinkedList<Fluido>();

    /**
     * Creates new form FrameFluidos
     */
    public FrameFluidos(JFrame frame) {
        //super(frame);
        initComponents();
        initComponentsView();
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tableFluidos = new javax.swing.JTable();
        buttonAdd = new javax.swing.JButton();
        buttonRemove = new javax.swing.JButton();
        buttonCancelar = new javax.swing.JButton();
        buttonGuardar = new javax.swing.JButton();

        setTitle("Editor de Fluidos");
        setResizable(false);

        tableFluidos.setModel(new FluidoModel(
            new Object [][] {

            },
            new String [] {
                "Nombre", "M", "SGG", "Z", "K", "Punto Inflamacion", "Punto Ebullicion", "Densidad", "SLG", "Calor latente Vaporizacion"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Double.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Double.class, java.lang.Double.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        tableFluidos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableFluidos.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tableFluidos);

        buttonAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aspneticons_v1.0_Nov2006/add_16x16.gif"))); // NOI18N
        buttonAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAddActionPerformed(evt);
            }
        });

        buttonRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aspneticons_v1.0_Nov2006/delete_16x16.gif"))); // NOI18N
        buttonRemove.setEnabled(false);
        buttonRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRemoveActionPerformed(evt);
            }
        });

        buttonCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aspneticons_v1.0_Nov2006/trash_16x16.gif"))); // NOI18N
        buttonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelarActionPerformed(evt);
            }
        });

        buttonGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/aspneticons_v1.0_Nov2006/save_16x16.gif"))); // NOI18N
        buttonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonGuardarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 767, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonRemove)
                        .addGap(0, 715, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(buttonGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonCancelar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonAdd)
                    .addComponent(buttonRemove))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonCancelar)
                    .addComponent(buttonGuardar))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-803)/2, (screenSize.height-494)/2, 803, 494);
    }// </editor-fold>//GEN-END:initComponents

    private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddActionPerformed
        Fluido fluido = new Fluido();
        ((FluidoModel) tableFluidos.getModel()).addRow(fluido);
        newObjects.add(fluido);
    }//GEN-LAST:event_buttonAddActionPerformed

    private void buttonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonGuardarActionPerformed
        ok = true;
        this.setVisible(false);
    }//GEN-LAST:event_buttonGuardarActionPerformed

    private void buttonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelarActionPerformed
        ok = false;
        this.setVisible(false);
    }//GEN-LAST:event_buttonCancelarActionPerformed

    private void buttonRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRemoveActionPerformed
        int row = tableFluidos.getSelectedRow();
        Fluido obj = (Fluido) tableFluidos.getValueAt(row, 0);
        if (newObjects.contains(obj)) {
            newObjects.remove(obj);
        } else {
            JPASession.getInstance().getManager().remove(obj);
        }
        ((FluidoModel) tableFluidos.getModel()).removeRow(row);
    }//GEN-LAST:event_buttonRemoveActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrameFluidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrameFluidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrameFluidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrameFluidos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAdd;
    private javax.swing.JButton buttonCancelar;
    private javax.swing.JButton buttonGuardar;
    private javax.swing.JButton buttonRemove;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tableFluidos;
    // End of variables declaration//GEN-END:variables

    private void initComponentsView() {
        List<Object> list = JPASession.getInstance().getResultListNamedQuery(Fluido.FIND_ALL);
        for (Object obj : list) {
            ((FluidoModel) tableFluidos.getModel()).addRow((Fluido) obj);
        }
        tableFluidos.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                boolean enable = false;
                if (tableFluidos.getSelectedRow() != -1) {
                    enable = true;
                }

            }
        });
    }

    @Override
    protected void saveNewObjects() {
        for (Fluido fluido : newObjects) {
            try {
                JPASession.getInstance().getManager().persist(fluido);
            } catch (Exception ex) {
                Logger.getLogger(FrameAceros.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
